﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using SilverlightPhoneDatabase;

namespace XBMCRemote.UseCase
{
    public class BaseUseCase<TEntity>
    {
        private const string DatabaseName = "XbmcRemote";
        private Database _database;

        public BaseUseCase()
        {
            SetDatabase();
        }

        private void SetDatabase()
        {
            if (!Database.DoesDatabaseExists(DatabaseName))
            {
                _database = Database.CreateDatabase(DatabaseName);
                _database.Save();
            }
            else
            {
                _database = Database.OpenDatabase(DatabaseName);
            }
        }

        public Database Database
        {
            get
            {
                return _database;
            }
        }

        /// <summary>
        /// Generic save function.
        /// </summary>
        /// <param name="entity">The entity to store.</param>
        public void Persist(TEntity entity)
        {
            Database.Table<TEntity>().Add(entity);
            Database.Save();
        }

        /// <summary>
        /// Generic update function.
        /// </summary>
        /// <param name="currentEntity">The entity to update.</param>
        /// <param name="entity">The updated entity.</param>
        public void Update(TEntity currentEntity, TEntity entity)
        {
            if (currentEntity != null)
            {
                Database.Table<TEntity>().Remove(currentEntity);
            }

            Database.Table<TEntity>().Add(entity);

            Database.Save();
        }
    }
}
